import '../utils/formatTime.js';
import DpModal from '../components-business/dp-modal/dp-modal.vue';
import { DproHeader } from "../components/index";
import PicPanelTitle from '../components-business/pic-panel-title.vue';
import PicList from '../components-business/pic-list.vue';
import { API_URLS } from '../api/index.js';
import { requestApi, formatCardProps } from "../utils/util";
import widgetConfig from '../widget.config.json';
let propsConfig = Object.assign({}, widgetConfig.props);
const MAX_LENGTH = 10

Widget({
  props: {
    config: {
      type: String,
      default: () => {
        return JSON.stringify({
          isPub: 2,
          roleType: 2, // 2 企业主
          userId: '',
          accessToken: 'P9z3NsDgWpcJDLRndq5hqzueAXkAWJkR', // 业务token
        })
      }
    },
    card: {
      type: String,
      default: () => {
        return JSON.stringify({})
      }
    }
  },
  data() {
    return {
      widgetConfig,
      propsConfig,
      picList: [],
      loading: false,
      deviceCodes: '',
      cardInfo: {},
      actIndex:0
    };
  },
  mounted() {
    // 读取卡片props初始化参数并保存到配置文件中
    this.cardInfo = formatCardProps(this.$props, { cardName: this.propsConfig.title });

    // 每隔60s刷新数据
    window.eventBus && window.eventBus.$on('card-refresh-timer', this.refresh)

    window.eventBus && window.eventBus.$on('j-push-msg', this.getWidgetData);
    this.getCardDeviceInfo()
  },
  methods: {
    tabsFn(index){
      console.log("切换",index)
      this.actIndex = index
    },
    // 挂载容器
    getPopupContainer() {
      return this.$refs.absContainer;
    },
    getCardDeviceInfo() {
      requestApi({
        url: API_URLS.getCardDeviceInfo,
        method: 'post',
        data: { screenId: this.cardInfo.screenId, cardId: this.cardInfo.cardId, cardSeq: this.cardInfo.index },
        headers: {
          AccessToken: this.cardInfo.accessToken
        }
      }).then(res => {
        if (res.code === 0) {
          if (res.data?.cardName) this.label = res.data.cardName
          this.deviceCodes = res.data?.deviceCodes
          this.fetchData();
        }
      })
    },

    async getWidgetData(message) {
      if (!Array.isArray(message)) {
        return;
      }
      if (message[0].extras.alertType === this.alertType) { // 15 口罩告警
        message[0].extras.formatTime = new Date(message[0].extras.alertTime).format('hh:mm:ss')
        let obj = {
          ...message[0].extras,
          alarmTime: message[0].extras.alertTime,
          imageUrl: null,
          catchPatImageUrl: null,
          bgImageUrl: null,
          id: String(message[0].extras.id),
          fromMsg: true,
          onload: false
        }
        if (this.deviceCodes) {
          if (!this.deviceCodes.includes(obj.deviceCode)) return;
        }
        this.picList.unshift(obj)
        let res = await this.getImgUrl(message[0].extras.id, obj.deviceCode);
        setTimeout(() => {
          obj.catchPatImageUrl = res?.catchPatImageUrl || ''
          obj.imageUrl = res?.imageUrl || ''
          obj.bgImageUrl = res?.bgImageUrl || ''
        }, 8000)
        if (this.picList.length > MAX_LENGTH) {
          this.picList.pop();
        }
      }
    },
    refresh() {
      this.getDataList();
    },
    async fetchData() {
      this.loading = true;
      await this.getDataList();
      this.loading = false
    },

    // 获取格式化业务响应数据
    async getDataList() {
      requestApi({
        url: API_URLS.getTypeInfo,
        method: 'post',
        data: {
          'queryParams': {
            "sceneType": 5 //疑似精神病
          }
        },
        headers: {
          AccessToken: this.cardInfo.accessToken
        }
      }).then(res => {
        var data = res.data.res;
        this.picList = JSON.parse(data)
      }).catch(err => {
        wgt.showMessage({
          title: err.msg,
          icon: 'error',
          duration: 3000
        });
      })
      /*this.picList = [
        {
          id:1,
          deviceCode:'deviceCode',
          alarmTime:'alarmTime',
          catchPatImageUrl:'https://img1.baidu.com/it/u=2387454115,4108876948&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1740157200&t=daef0767fd9b354586db87388265af32'
        },
        {
          id:2,
          deviceCode:'deviceCode',
          alarmTime:'alarmTime',
          deviceName:'deviceName',
          catchPatImageUrl:'https://img1.baidu.com/it/u=2387454115,4108876948&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1740157200&t=daef0767fd9b354586db87388265af32'
        },
        {
          id:3,
          deviceCode:'deviceCode',
          alarmTime:'alarmTime',
          deviceName:'deviceName',
          catchPatImageUrl:'https://img1.baidu.com/it/u=2387454115,4108876948&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1740157200&t=daef0767fd9b354586db87388265af32'
        },
        {
          id: 4,
          deviceCode: 'deviceCode',
          alarmTime: 'alarmTime',
          deviceName: 'deviceName',
          catchPatImageUrl: 'https://img1.baidu.com/it/u=2387454115,4108876948&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1740157200&t=daef0767fd9b354586db87388265af32'
        },
        {
          id: 5,
          deviceCode: 'deviceCode',
          alarmTime: 'alarmTime',
          deviceName: 'deviceName',
          catchPatImageUrl: 'https://img1.baidu.com/it/u=2387454115,4108876948&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1740157200&t=daef0767fd9b354586db87388265af32'
        }
      ]*/
    },

    open(item) {
      // this.$refs.picModal?.open(item);
      this.$refs.imgModal?.openPreview('https://dianxin.minio.xiangshilian.com:9001/'+item.bgImageUrl);
    },
    openImg(imageUrl) {
      this.$refs.imgModal?.openPreview(imageUrl);
    },
    openWin() {
      window.eventBus && window.eventBus.$emit('navigate-router', this.widgetConfig.routerConfig)
    },
    // 根据id获取接口配置信息
    getDataSourceById(id) {
      return this.widgetConfig.dataSource.find(it => it.id === id);
    },
    /**
     * 获取接口响应数据，支持动态接口(extraParam为业务扩展请求参数)和静态数据
     * @param {String} id 接口配置id，唯一标识
     * @param {Object} extraParam 业务扩展请求参数
     * @returns {Object} result
     *    result.type: 'api'动态接口请求模式，'static'静态数据
     *    result.data: 数据详情
     */
    async getDataSourceResult(id, extraParam = {}) {
      let conf = this.getDataSourceById(id);
      if (!conf) return { code: -2, msg: '缺少接口配置' };
      const { request = {}, data = {} } = conf;
      // 动态接口请求
      if (request.url) {
        const res = await requestApi({
          ...request,
          data: {
            ...(request.data || {}),
            ...extraParam
          },
          headers: {
            AccessToken: this.cardInfo.accessToken,
            ...(request.headers || {})
          }
        })
        return { type: 'api', data: res };
      } else {
        // 静态数据
        return { type: 'static', data };
      }
    },
  },
  beforeDestroy() {
    window.eventBus && window.eventBus.$off('card-refresh-timer', this.refresh)

    window.eventBus && window.eventBus.$off('j-push-msg', this.getWidgetData);
  },
  components: {
    PicPanelTitle,
    PicList,
    DpModal,
    DproHeader
  },
});
